<template>
  <BasicModal @register="registerModal" :title="title" :width="width" @ok="handleSubmit" wrapClassName="jeecg-online-modal" :style="modalStyle">
    <template #footer>
      <a-button type="primary" @click="handleSubmit">确定</a-button>
      <a-button @click="handleCancel">关闭</a-button>
    </template>
    <template #default>
      <a-spin :spinning="confirmLoading">
        <online-form
          v-if="isOnlineForm"
          ref="onlineFormCompRef"
          id="id"
          :form-template="formTemplate"
          @rendered="renderSuccess"
          @success="handleSuccess"
        />
        <resolveDynamicComponent v-else ref="customFormRef" :url="customFormComponent.url" :row="customFormComponent.row" close="handleSuccess" />
      </a-spin>
    </template>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, nextTick, watch, reactive, markRaw, defineAsyncComponent, resolveDynamicComponent } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { getRefPromise } from '../../use/useAutoForm';
  import { defHttp } from '/@/utils/http/axios';
  import OnlineForm from '../comp/OnlineForm.vue';
  import { importViewsFile } from '/@/utils';

  const DEF_CONFIG = {
    code: '',
    title: '自定义弹框',
    width: 600,
    row: {},
    hide: [],
    show: [],
    requestUrl: '',
    tableType: '',
    foreignKeys: '',
    formComponent: '',
  };

  export default defineComponent({
    name: 'OnlineCustomModal',
    components: {
      OnlineForm,
      BasicModal,
      resolveDynamicComponent,
    },
    setup(_props, { emit }) {
      const onlineFormCompRef = ref();
      const id = ref('');
      const title = ref('自定义弹框');
      const width = ref(600);
      let onlineHideFields = [];
      let onlineShowFields = [];
      let onlineFormEditUrl = '';
      let currentRowData = {};
      const url = {
        loadFormItems: '/api-online/online/cgform/api/getFormItem/',
        optPre: '/api-online/online/cgform/api/form/',
      };
      const modalStyle = { position: 'relative' };
      const confirmLoading = ref(false);
      const formRendered = ref(false);
      function renderSuccess() {
        formRendered.value = true;
      }
      const isOnlineForm = ref(true);
      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (params) => {
        setModalProps({ confirmLoading: false });
        resetParams(params);
        await nextTick(async () => {
          if (!params.formComponent) {
            await showOnlineForm();
          } else {
            showCustomForm(params.formComponent);
          }
        });
      });
      function resetParams(params) {
        let options = Object.assign({}, DEF_CONFIG, params);
        id.value = options.code;
        title.value = options.title;
        width.value = options.width;
        onlineHideFields = options.hide || [];
        onlineShowFields = options.show || [];
        onlineFormEditUrl = getOnlineFormEditUrl(options.requestUrl);
        currentRowData = options.row;
      }
      function getOnlineFormEditUrl(requestUrl) {
        if (requestUrl) {
          return requestUrl;
        } else {
          return url.optPre + id.value;
        }
      }
      const submitLoading = ref(false);
      function handleSubmit() {
        submitLoading.value = true;
        if (isOnlineForm.value === true) {
          onlineFormCompRef.value.handleSubmit();
        } else {
          customFormRef.value.handleSubmit();
        }
        setTimeout(() => {
          submitLoading.value = true;
        }, 3500);
      }
      function handleCancel() {
        closeModal();
      }
      function handleSuccess(formData) {
        emit('success', formData);
        closeModal();
      }
      async function showOnlineForm() {
        isOnlineForm.value = true;
        await getRefPromise(formRendered);
        onlineFormCompRef.value.handleCustomFormSh(onlineShowFields, onlineHideFields);
        onlineFormCompRef.value.handleCustomFormEdit(currentRowData, onlineFormEditUrl);
      }
      const formTemplate = ref(1);
      watch(id, renderFormItems, { immediate: true });
      async function renderFormItems() {
        formRendered.value = false;
        if (!id.value) {
          return;
        }
        console.log('重新渲染表单》》》》modal');
        let result = await loadFormItems();
        let dataFormTemplate = result.head.formTemplate;
        formTemplate.value = dataFormTemplate ? Number(dataFormTemplate) : 1;
        nextTick(async () => {
          let myForm = await getRefPromise(onlineFormCompRef);
          myForm.createRootProperties(result);
        });
      }
      function loadFormItems() {
        let url2 = `/api-online/online/cgform/api/getFormItem/${id.value}`;
        return new Promise((resolve, reject) => {
          defHttp
            .get({ url: url2 }, { isTransformResponse: false })
            .then((res) => {
              console.log('表单结果》》modal:', res);
              if (res.success) {
                resolve(res.data);
              } else {
                reject(res.msg);
              }
            })
            .catch(() => {
              reject();
            });
        });
      }
      const customFormRef = ref();
      const customFormComponent = reactive({
        url: '',
        is: '',
        row: {},
      });
      function showCustomForm(formComponent) {
        isOnlineForm.value = false;
        customFormComponent.url = onlineFormEditUrl;
        customFormComponent.row = currentRowData;
        customFormComponent.is = markRaw(defineAsyncComponent(() => importViewsFile(formComponent)));
      }
      return {
        registerModal,
        title,
        width,
        modalStyle,
        handleSubmit,
        handleCancel,
        id,
        onlineFormCompRef,
        formTemplate,
        renderSuccess,
        customFormRef,
        customFormComponent,
        open,
        isOnlineForm,
        confirmLoading,
        submitLoading,
        handleSuccess,
      };
    },
  });
</script>
<style scoped></style>
